#!/usr/bin/env python3
"""
XCQuant 策略运行主程序

整合所有模块，实现完整的量化交易系统
"""

import sys
import os
import time
import signal
import threading
from typing import Dict, Any, Optional

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from xcquant.core import config_manager, unified_logger
from xcquant.exchanges.okx_adapter import OKXAdapter
from xcquant.exchanges.binance_adapter import BinanceAdapter
from xcquant.trading.order_manager import OrderManager
from xcquant.trading.account_manager import AccountManager
from xcquant.data.data_manager import DataManager
from xcquant.strategies.grid_strategy import GridStrategy
from xcquant.monitor.monitor import Monitor


class XCQuantRunner:
    """XCQuant 主运行器"""
    
    def __init__(self):
        """初始化运行器"""
        self.logger = unified_logger.get_logger('xcquant_runner')
        self.config_manager = ConfigManager()
        
        # 核心组件
        self.exchanges = {}
        self.order_manager = None
        self.account_manager = None
        self.data_manager = None
        self.monitor = None
        
        # 策略管理
        self.strategies: Dict[str, Any] = {}
        self.running = False
        
        # 监控线程
        self.monitor_thread: Optional[threading.Thread] = None
        
        self.logger.info("XCQuant 运行器初始化完成")
    
    def initialize(self) -> bool:
        """初始化所有组件"""
        try:
            self.logger.info("开始初始化XCQuant系统...")
            
            # 1. 初始化核心组件
            self.order_manager = OrderManager()
            self.account_manager = AccountManager()
            self.data_manager = DataManager()
            
            # 2. 初始化交易所适配器
            self._initialize_exchanges()
            
            # 3. 注册交易所到数据管理器
            for exchange_name, exchange_adapter in self.exchanges.items():
                self.data_manager.register_exchange(exchange_name, exchange_adapter)
            
            # 4. 初始化监控系统
            self.monitor = Monitor(update_interval=3)
            self.monitor.add_data_callback(self._get_monitor_data)
            
            # 5. 设置信号处理
            signal.signal(signal.SIGINT, self._signal_handler)
            signal.signal(signal.SIGTERM, self._signal_handler)
            
            self.logger.info("XCQuant系统初始化完成")
            return True
            
        except Exception as e:
            self.logger.error(f"系统初始化失败: {e}")
            return False
    
    def _initialize_exchanges(self) -> None:
        """初始化交易所适配器"""
        try:
            # 初始化OKX
            okx_config = self.config_manager.get_exchange_config('okx')
            if okx_config.get('api_key'):
                self.exchanges['okx'] = OKXAdapter(okx_config)
                self.logger.info("OKX交易所适配器初始化成功")
            
            # 初始化币安
            binance_config = self.config_manager.get_exchange_config('binance')
            if binance_config.get('api_key'):
                self.exchanges['binance'] = BinanceAdapter(binance_config)
                self.logger.info("币安交易所适配器初始化成功")
            
            if not self.exchanges:
                raise Exception("没有可用的交易所配置")
                
        except Exception as e:
            self.logger.error(f"交易所初始化失败: {e}")
            raise
    
    def create_strategy(self, strategy_config: Dict[str, Any]) -> bool:
        """
        创建策略
        
        Args:
            strategy_config: 策略配置
            
        Returns:
            是否创建成功
        """
        try:
            strategy_name = strategy_config.get('name')
            strategy_type = strategy_config.get('class', 'GridStrategy')
            exchange_name = strategy_config.get('exchange')
            
            if not strategy_name:
                raise ValueError("策略名称不能为空")
            
            if exchange_name not in self.exchanges:
                raise ValueError(f"交易所 {exchange_name} 未配置")
            
            # 获取交易所适配器
            exchange_adapter = self.exchanges[exchange_name]
            
            # 创建策略实例
            if strategy_type == 'GridStrategy':
                strategy = GridStrategy(
                    config=strategy_config,
                    exchange_adapter=exchange_adapter,
                    order_manager=self.order_manager,
                    account_manager=self.account_manager,
                    data_manager=self.data_manager
                )
            else:
                raise ValueError(f"不支持的策略类型: {strategy_type}")
            
            self.strategies[strategy_name] = strategy
            self.logger.info(f"策略 {strategy_name} 创建成功")
            
            return True
            
        except Exception as e:
            self.logger.error(f"创建策略失败: {e}")
            return False
    
    def start_strategy(self, strategy_name: str) -> bool:
        """
        启动策略
        
        Args:
            strategy_name: 策略名称
            
        Returns:
            是否启动成功
        """
        try:
            if strategy_name not in self.strategies:
                raise ValueError(f"策略 {strategy_name} 不存在")
            
            strategy = self.strategies[strategy_name]
            success = strategy.start()
            
            if success:
                self.logger.info(f"策略 {strategy_name} 启动成功")
            else:
                self.logger.error(f"策略 {strategy_name} 启动失败")
            
            return success
            
        except Exception as e:
            self.logger.error(f"启动策略失败: {e}")
            return False
    
    def stop_strategy(self, strategy_name: str) -> bool:
        """
        停止策略
        
        Args:
            strategy_name: 策略名称
            
        Returns:
            是否停止成功
        """
        try:
            if strategy_name not in self.strategies:
                raise ValueError(f"策略 {strategy_name} 不存在")
            
            strategy = self.strategies[strategy_name]
            success = strategy.stop()
            
            if success:
                self.logger.info(f"策略 {strategy_name} 停止成功")
            else:
                self.logger.error(f"策略 {strategy_name} 停止失败")
            
            return success
            
        except Exception as e:
            self.logger.error(f"停止策略失败: {e}")
            return False
    
    def start_monitoring(self) -> bool:
        """启动监控系统"""
        try:
            if self.monitor:
                success = self.monitor.start()
                if success:
                    self.logger.info("监控系统启动成功")
                return success
            return False
            
        except Exception as e:
            self.logger.error(f"启动监控系统失败: {e}")
            return False
    
    def _get_monitor_data(self) -> Dict[str, Any]:
        """获取监控数据"""
        try:
            data = {
                'strategies': {},
                'accounts': {},
                'orders': {},
                'system': {}
            }
            
            # 策略数据
            for name, strategy in self.strategies.items():
                data['strategies'][name] = strategy.get_stats()
            
            # 账户数据
            if self.account_manager:
                data['accounts'] = self.account_manager.get_all_accounts()
            
            # 订单数据
            if self.order_manager:
                recent_orders = self.order_manager.get_recent_orders(20)
                data['orders'] = {order['order_id']: order for order in recent_orders}
            
            # 系统数据
            data['system'] = {
                'active_strategies': len([s for s in self.strategies.values() if s.is_running()]),
                'total_exchanges': len(self.exchanges),
                'performance': self._get_system_performance()
            }
            
            return data
            
        except Exception as e:
            self.logger.error(f"获取监控数据失败: {e}")
            return {}
    
    def _get_system_performance(self) -> Dict[str, float]:
        """获取系统性能信息"""
        try:
            import psutil
            return {
                'cpu_percent': psutil.cpu_percent(interval=1),
                'memory_percent': psutil.virtual_memory().percent
            }
        except ImportError:
            return {'cpu_percent': 0.0, 'memory_percent': 0.0}
        except Exception:
            return {'cpu_percent': 0.0, 'memory_percent': 0.0}
    
    def run(self) -> None:
        """运行主循环"""
        try:
            self.running = True
            self.logger.info("XCQuant系统开始运行")
            
            # 启动监控系统
            self.start_monitoring()
            
            # 主循环
            while self.running:
                try:
                    # 更新账户信息
                    self._update_account_info()
                    
                    # 检查策略状态
                    self._check_strategies()
                    
                    # 等待下次循环
                    time.sleep(5)
                    
                except KeyboardInterrupt:
                    self.logger.info("接收到中断信号，准备退出...")
                    break
                except Exception as e:
                    self.logger.error(f"主循环异常: {e}")
                    time.sleep(1)
            
            self.logger.info("XCQuant系统运行结束")
            
        except Exception as e:
            self.logger.error(f"系统运行失败: {e}")
        finally:
            self.shutdown()
    
    def _update_account_info(self) -> None:
        """更新账户信息"""
        try:
            for exchange_name, exchange_adapter in self.exchanges.items():
                try:
                    # 更新现货账户
                    spot_balance = exchange_adapter.get_spot_balance()
                    if spot_balance:
                        self.account_manager.update_spot_balance(exchange_name, spot_balance)
                    
                    # 更新合约账户
                    futures_balance = exchange_adapter.get_futures_balance()
                    if futures_balance:
                        self.account_manager.update_futures_balance(exchange_name, futures_balance)
                        
                except Exception as e:
                    self.logger.warning(f"更新 {exchange_name} 账户信息失败: {e}")
                    
        except Exception as e:
            self.logger.error(f"更新账户信息失败: {e}")
    
    def _check_strategies(self) -> None:
        """检查策略状态"""
        try:
            for strategy_name, strategy in self.strategies.items():
                if strategy.is_running():
                    # 获取最新价格并触发策略更新
                    try:
                        latest_price = strategy.get_latest_price()
                        if latest_price:
                            strategy.on_tick({'price': latest_price})
                    except Exception as e:
                        self.logger.warning(f"策略 {strategy_name} 价格更新失败: {e}")
                        
        except Exception as e:
            self.logger.error(f"检查策略状态失败: {e}")
    
    def _signal_handler(self, signum, frame):
        """信号处理器"""
        self.logger.info(f"接收到信号 {signum}，准备退出...")
        self.running = False
    
    def shutdown(self) -> None:
        """关闭系统"""
        try:
            self.logger.info("开始关闭XCQuant系统...")
            
            # 停止所有策略
            for strategy_name in list(self.strategies.keys()):
                self.stop_strategy(strategy_name)
            
            # 停止监控系统
            if self.monitor:
                self.monitor.stop()
            
            self.logger.info("XCQuant系统关闭完成")
            
        except Exception as e:
            self.logger.error(f"系统关闭失败: {e}")


def main():
    """主函数"""
    print("=" * 60)
    print("XCQuant 量化交易系统")
    print("=" * 60)
    
    # 创建运行器
    runner = XCQuantRunner()
    
    try:
        # 初始化系统
        if not runner.initialize():
            print("❌ 系统初始化失败")
            return False
        
        print("✅ 系统初始化成功")
        
        # 创建示例网格策略
        grid_config = {
            'name': 'btc_grid_strategy',
            'class': 'GridStrategy',
            'symbol': 'btc-usdt',
            'exchange': 'okx',
            'type': 'spot',
            'grid_count': 10,
            'price_min': 0.0,  # 自动计算
            'price_max': 0.0,  # 自动计算
            'single_grid_amount': 50.0,
            'stop_loss_ratio': 0.05,
            'leverage': 1,
            'interval': '5m'
        }
        
        # 创建策略
        if runner.create_strategy(grid_config):
            print("✅ 网格策略创建成功")
            
            # 启动策略
            if runner.start_strategy('btc_grid_strategy'):
                print("✅ 网格策略启动成功")
            else:
                print("⚠️  网格策略启动失败")
        else:
            print("❌ 网格策略创建失败")
        
        print("\n🚀 系统开始运行...")
        print("按 Ctrl+C 退出系统")
        
        # 运行系统
        runner.run()
        
        return True
        
    except KeyboardInterrupt:
        print("\n👋 用户中断，系统退出")
        return True
    except Exception as e:
        print(f"❌ 系统运行异常: {e}")
        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)